package com.lanyun.config;


import com.lanyun.core.encrypt.handler.EncryptHandler;
import com.lanyun.core.encrypt.handler.EncryptTypeHandler;
import com.lanyun.core.encrypt.properties.EncryptProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @ClassName：EncryptAutoConfiguration
 * @Description: 加密自动配置
 * @Author: Jqcc
 * @Date: 2025/3/13
 */
@Configuration
@MapperScan("com.lanyun.*.basic.dao")
@EnableConfigurationProperties({EncryptProperties.class})
public class EncryptAutoConfiguration {

    @Bean
    @ConditionalOnProperty(name = "ly.encrypt.enabled", havingValue = "true", matchIfMissing = false)
    public EncryptTypeHandler encryptTypeHandler() {
        return new EncryptTypeHandler();
    }

    @Resource
    private EncryptProperties encryptProperties;

    @Bean
    @ConditionalOnMissingBean(EncryptHandler.class)
    @ConditionalOnProperty(name = "ly.encrypt.enabled", havingValue = "true", matchIfMissing = false)
    public EncryptHandler encryptHandler() {
        String algorithmHandler = encryptProperties.getAlgorithmHandler();
        Class<?> algorithmHandlerClass;
        EncryptHandler encryptHandler = null;
        try {
            algorithmHandlerClass = Class.forName(algorithmHandler);
            // 使用无参数构造函数创建对象
            encryptHandler = (EncryptHandler) algorithmHandlerClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return encryptHandler;
    }

}

